package com.erlinyou.im.dao.repository.chat;

import java.util.List;

import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import com.erlinyou.base.dao.BaseRepository;
import com.erlinyou.im.model.chat.ChatSessionKey;
import com.erlinyou.im.model.chat.ChatSession;


public interface ChatSessionRepository extends BaseRepository<ChatSession, ChatSessionKey> {
	
	public List<ChatSession> findByUseridOrderByUptimeDesc(Long userid);
	
	@Transactional
	public int deleteByUseridAndRidAndCtype(Long userid, Long rid,Integer ctype);
	
//	@Query(value = "SELECT c.userid,c.rid,c.uptime,c.type,c.content,c.noreadnum,t.image,t.nickName from erlinyou_im.tchat_session c LEFT JOIN etravel.tuser t ON c.rid = t.userid where c.userid = ?1",nativeQuery=true)
//	public List<Map<String, Object>> findByUseridJoinUser(String userId);
	
	@Modifying
	@Query(value="INSERT into tchat_session(userid,rid,uptime,ctype,content,noreadnum) VALUES( ?#{#chatSession.userid}, ?#{#chatSession.rid}, ?#{#chatSession.uptime},?#{#chatSession.ctype}, ?#{#chatSession.content},?#{#chatSession.noreadnum}) "
			+ "ON DUPLICATE KEY UPDATE uptime= ?#{#chatSession.uptime},content= ?#{#chatSession.content},noreadnum=if( ?#{#chatSession.noreadnum},noreadnum+1,0)",nativeQuery=true)
	public int updateChatSession(@Param("chatSession") ChatSession chatSession);

	
	/**
	 * 撤回的消息,更新最近会话
	 * 1	更新会话内容
	 * 2	更新会话未读数
	 * @param chatSession
	 * @return
	 */
	@Modifying
	@Query(value="UPDATE tchat_session set content= ?#{#chatSession.content},noreadnum=if( ?#{#chatSession.noreadnum},if(noreadnum-1>=0,noreadnum-1,0),0) where userid = ?#{#chatSession.userid} and rid = ?#{#chatSession.rid}",nativeQuery=true)
	public int updateRevokeChatSession(@Param("chatSession") ChatSession chatSession);

	@Modifying
	@Query(value="UPDATE tchat_session set noreadnum = 0 where userid = ?1 and rid = ?2 and ctype = ?3",nativeQuery=true)
	public void cleanNoReadNum(Long userId, Long rid, Integer ctype);

	public List<ChatSession> findByUseridAndRidAndCtype(Long userId, long rid, int i);

	@Transactional
	public int deleteByRidAndCtype(long longValue, int i);
}
